﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CrystalCore.Mapping;
using CrystalCore.Structure;
using DeenGames.Utils.AStarPathFinder;

namespace CrystalCore.AI
{
    public static class AStarSolver
    {
        public static IEnumerable<MazePosition> FindPath(LevelMap map, MazePosition start, MazePosition finish)
        {
            int width = map.MapWidth;
            int height = map.MapDepth;

            width = PathFinderHelper.RoundToNearestPowerOfTwo(width);
            height = PathFinderHelper.RoundToNearestPowerOfTwo(height);

            byte[,] grid = new byte[width, height];

            for (int y = 0; y < height; y++)
            {
                for (int x = 0; x < width; x++)
                {
                    if (map.CanUserWalk(x, y))
                        grid[x, y] = PathFinderHelper.EMPTY_TILE;
                    else
                        grid[x, y] = PathFinderHelper.BLOCKED_TILE;
                }
            }

            PathFinderFast pfinder = new PathFinderFast(grid);
            pfinder.Diagonals = false;
            List<PathFinderNode> path = pfinder.FindPath(
                new DeenGames.Utils.Point(start.X, start.Z),
                new DeenGames.Utils.Point(finish.X, finish.Z));

            if (path == null)
                return null;
            else
                return path.Select(p => { return new MazePosition(p.X, p.Y); });
        }
    }
}
